/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.util;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class TimeChecker extends TimerTask {

    private final Logger logger = LoggerFactory.getLogger(TimeChecker.class);
    private DateFormat referenceDateFormat;
    private Calendar referenceTime;
    private ExecutorService executor;
    private List<Runnable> tasks;

    public TimeChecker(DateFormat referenceDateFormat, Calendar referenceTime, ExecutorService executor, List<Runnable> tasks) {
        this.referenceDateFormat = referenceDateFormat;
        this.referenceTime = referenceTime;
        this.executor = executor;
        this.tasks = tasks;
    }

    public TimeChecker(DateFormat referenceDateFormat, Calendar referenceTime, List<Runnable> tasks) {
        this.referenceDateFormat = referenceDateFormat;
        this.referenceTime = referenceTime;
        this.tasks = tasks;
    }

    @Override
    public void run() {
        try {
            Calendar currentTime = Calendar.getInstance();
            String refTimeString = referenceDateFormat.format(referenceTime.getTime());
            String curTimeString = referenceDateFormat.format(currentTime.getTime());
            if (refTimeString.equals(curTimeString)) {
                if (executor == null || executor.isShutdown()) {
                    executor = Executors.newFixedThreadPool(tasks.size());
                }
                
                for (Runnable task : tasks) {
                    executor.execute(task);
                }
            }
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }
}
